{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Continuous-Time Meta-Learning with Forward Mode Differentiation\n",
    "\n",
    "This notebook contains an example of how to meta-train COMLN. We will use the preprocessed version of miniImageNet as an example, introduced in ([Rusu et al., 2018](https://arxiv.org/abs/1807.05960)), with 5-way 5-shot classification tasks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import jax.numpy as jnp\n",
    "import haiku as hk\n",
    "import optax\n",
    "import math\n",
    "\n",
    "from tqdm.auto import tqdm\n",
    "from scipy.stats import t\n",
    "from jax import random\n",
    "from jax_meta.datasets import LEOMiniImagenet\n",
    "\n",
    "from comln import COMLN, COMLNMetaParameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "meta_train_dataset = LEOMiniImagenet(\n",
    "    root='data/',\n",
    "    batch_size=16,\n",
    "    shots=5,\n",
    "    ways=5,\n",
    "    test_shots=15,\n",
    "    size=2000,\n",
    "    split='train',\n",
    "    seed=0,\n",
    "    download=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since the data has already been preprocessed, there is no need for a feature extraction network. Therefore the model here is simply the identity function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@hk.without_apply_rng\n",
    "@hk.transform_with_state\n",
    "def model(inputs):\n",
    "    return inputs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "key = random.PRNGKey(0)\n",
    "\n",
    "optimizer = optax.multi_transform({\n",
    "    'model': optax.sgd(1e-1, momentum=0.9, nesterov=True),\n",
    "    'classifier': optax.sgd(1e-1, momentum=0.9, nesterov=True),\n",
    "    't_final': optax.sgd(1e-1, momentum=0.9, nesterov=True)\n",
    "}, COMLNMetaParameters(model='model', classifier='classifier', t_final='t_final'))\n",
    "\n",
    "metalearner = COMLN(\n",
    "    model,\n",
    "    num_ways=meta_train_dataset.ways,\n",
    "    t_final=1.,\n",
    "    odeint_kwargs='{\"atol\":1e-5,\"rtol\":1e-5}'\n",
    ")\n",
    "\n",
    "params, state = metalearner.init(key, optimizer, meta_train_dataset.dummy_input)\n",
    "\n",
    "with tqdm(meta_train_dataset, desc='Meta-train') as pbar:\n",
    "    for batch in pbar:\n",
    "        params, state, logs = metalearner.step(params, state, batch['train'], batch['test'])\n",
    "        pbar.set_postfix(\n",
    "            T=f'{jnp.exp(params.t_final):.2f}',\n",
    "            accuracy=f'{100 * logs[\"outer/accuracy\"].mean():.2f}',\n",
    "        )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "meta_test_dataset = LEOMiniImagenet(\n",
    "    root='data/',\n",
    "    batch_size=10,\n",
    "    shots=5,\n",
    "    ways=5,\n",
    "    test_shots=15,\n",
    "    size=100,\n",
    "    split='test',\n",
    "    seed=0\n",
    ")\n",
    "\n",
    "results = metalearner.evaluate(params, state, meta_test_dataset)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "accuracy = results['outer/accuracy']\n",
    "print(f'Accuracy: {results[\"outer/accuracy\"] * 100:.2f}%')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "11668e9782cd173820513433ff25e0f29c6e7ec9acda339bec9d4200dd9e515d"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
